import { getHeroListAPI } from "../api/hero"
import Variable from "../constants/index"
import { Hero } from "../types/hero"

// pages/search/search.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchWordList:[
    ] as string[],
    word:'',
    heroList:[] as Hero[]
  },
  async search(){
    if (this.data.word) {
      wx.showLoading({title:'查询中'})
      const list = await getHeroListAPI({ q:this.data.word })
    this.setData({
      heroList:list,
      searchWordList:[...new Set([this.data.word,...this.data.searchWordList])] 
    },()=>{
      console.log(this.data.searchWordList)
      wx.setStorageSync(Variable.SEARCH_WORD_KEY,JSON.stringify(this.data.searchWordList))
      wx.hideLoading()
    })
    }else{
      this.setData({
        heroList:[]
      })
    }
  },
  // 点击搜索记录搜索
  searchWord(event:WechatMiniprogram.TouchEvent){
    this.setData({
      word:event.mark?.word
    },()=>{
      this.search()
    })
  },
  // 删除单个搜索记录
  delWord(event:WechatMiniprogram.TouchEvent){
    this.setData({
      searchWordList:this.data.searchWordList.filter(item=>item !== event.mark?.word)
    },()=>{
      wx.setStorageSync(Variable.SEARCH_WORD_KEY,JSON.stringify(this.data.searchWordList))
    })
  },
  // 删除所有记录
  delAll(){
    this.setData({
      searchWordList:[]
    },()=>{
      wx.removeStorageSync(Variable.SEARCH_WORD_KEY)
    })
  },
  toDetail(event:WechatMiniprogram.TouchEvent){
    wx.navigateTo({
    url:`/pages/hero_detail/hero_detail?heroId=${event.mark?.heroId}`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getList()
  },
  getList(){
    this.setData({
      searchWordList:JSON.parse( wx.getStorageSync(Variable.SEARCH_WORD_KEY) || '[]') as string[]
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})